<?php
    include(dirname(__FILE__)."/../../../Dao/db.php");

    class CampaignService
    {
        var $memberId;
        //メディアー種類
        var $listingType;
        //キャンペーンID
        var $camp_Id;
        //キャンペーン名
        var $campaignName;
        //キャンペーン概要
        var $campaignSummarize;
        //開始日
        var $startDate;
        var $startHour;
        var $startMin;
        var $startSec;
        //終了日
        var $endDate;
        var $endHour;
        var $endMin;
        var $endSec;
        //ネットワック設定
        var $networkTargeting;
        //
        var $isEnableSeperateContentBids;
        //自動最適化
        var $isEnableAutoOptimization;
        //掲載状態
        var $status;
        //一日の予算
        var $dailyBudget;
        //アラート設定
        var $budgetSpan;
        var $budget;
        //アラート対象の乖離率
        var $budgetLimit;

        function CampaignService()
        {
            session_start();
            $this->memberId = $_SESSION['memberId'];
            $this->listingType = $_GET['listingType'];
            $this->camp_Id = $_GET['campaignId'];
            $this->campaignName = $_POST['campaign_name'];
            $this->campaignSummarize = $_POST['campaign_summarize'];
            $this->startDate = $_POST['start_date'];
            $this->startHour = $_POST['start_hour'];
            $this->startMin = $_POST['start_min'];
            $this->startSec = $_POST['start_sec'];
            $this->endDate = $_POST['end_date'];
            $this->endHour = $_POST['end_hour'];
            $this->endMin = $_POST['end_min'];
            $this->endSec = $_POST['end_sec'];

            if(isset($_POST['googleSearch']))
            {
                $this->networkTargeting = "GoogleSearch";
            }
            if(isset($_POST['partnerSearch']))
            {
                if(isset($this->networkTargeting))
                {
                    $this->networkTargeting = "SearchNetwork";
                }
            }

            if(isset($_POST['contentSearch']))
            {
                if(isset($this->networkTargeting))
                {
                    $this->networkTargeting .= ",ContentNetwork";
                }
                else
                {
                    $this->networkTargeting = "ContentNetwork";
                }
            }

            if(isset($_POST['enableContentBids']))
            {
                $this->isEnableSeperateContentBids = 1;
            }
            else
            {
                $this->isEnableSeperateContentBids = 0;
            }

            if(isset($_POST['auto_optimization']))
            {
                $this->isEnableAutoOptimization = 1;
            }
            else
            {
                $this->isEnableAutoOptimization = 0;
            }

            $this->status = $_POST['status'];
            $this->dailyBudget = $_POST['budget_daily'];
            $this->budgetSpan = $_POST['budget_span'];
            if(isset($_POST['budget']) && $_POST['budget'] != "")
            {
                $this->budget = $_POST['budget'];
            }
            else
            {
                $this->budget = 0;
            }
            if(isset($_POST['budget_limit']) && $_POST['budget_limit'] != "")
            {
                $this->budgetLimit = $_POST['budget_limit'];
            }
            else
            {
                $this->budgetLimit = 0;
            }
        }

        //同期エラーを表示する
        function getErrorMessage()
        {
            $query = "SELECT syncError FROM campaign ";
            $query .= "WHERE camp_Id=$this->camp_Id ";
            $query .= "AND sync=3 ";

            $result = mysql_query($query);
            $row = mysql_fetch_array($result);
            $syncError = trim($row['syncError']);
            if($syncError)
            {
                $errorTable = "<br><table class='tbl' width='100%' border='0' cellpadding='4' cellspacing='0'>";
                $errorTable .= "<tbody><tr>";
                $errorTable .= "<td class='td9' width='150' align='left'>";
                $errorTable .= "<img src='../images/sync_error.gif' border='0'>エラー</td>";
                $errorTable .= "<td class='td4 left'><pre>".$syncError."</pre></td>";
                $errorTable .= "</tr></tbody>";
                $errorTable .= "</table><br>";
            }

            echo $errorTable;
        }

        function addCampaign()
        {
            //まず、同じキャンペーン名チェック
            $query = "SELECT * FROM campaign WHERE ";
            $query .= "memberId=$this->memberId AND ";
            $query .= "listingType=$this->listingType AND ";
            $query .= "name='$this->campaignName' AND ";
            $query .= "status!=9";

            $result = mysql_query($query);
            //同じキャンペーン名がある場合、新規できません
            if(mysql_fetch_array($result))
            {
                $message = "同じキャンペーン名がある";
            }
            else
            {
                $query = "INSERT INTO campaign(MemberID,listingType,name,summarize,startDay,";
                if($this->endDate != "")
                {
                    $query .= "endDay,";
                }
                $query .= "networkTargeting,enableSeparateContentBids,";
                $query .= "enableBudgetOptimizer,status,";
                $query .= "dailyBudget,sync,registDate,lastUpdate) ";
                $query .= "VALUES($this->memberId,";
                $query .= "$this->listingType,";
                $query .= "'$this->campaignName',";
                $query .= "'$this->campaignSummarize',";
                $query .= "'$this->startDate $this->startHour:$this->startMin:$this->startSec',";
                if($this->endDate != "")
                {
                    $query .= "'$this->endDate $this->endHour:$this->endMin:$this->endSec',";
                }
                $query .= "'$this->networkTargeting',";
                $query .= "$this->isEnableSeperateContentBids,";
                $query .= "$this->isEnableAutoOptimization,";
                $query .= "$this->status,";
                $query .= "$this->dailyBudget,";
                //同期状態は未同期
                $query .= "2,";
                $query .= "now(),now())";
                $result = mysql_query($query);
                if ($result != "1")
                {
                    $message = "登録失敗しました";
                    return $message;
                }
                else
                {
                    $message = "登録しました";
                }
                
                $query = "SELECT camp_Id FROM campaign WHERE ";
                $query .= "name='$this->campaignName' AND ";
                $query .= "memberId=$this->memberId AND ";
                $query .= "listingType=$this->listingType AND ";
                $query .= "status!=9";
                $result = mysql_query($query);
                $row = mysql_fetch_array($result);
                $camp_Id = $row['camp_Id'];

                //アラーと情報を入力
                $query = "INSERT INTO alertschedule (campaignId,period,alertBudget,conversionPremium,registDate,lastUpdate) VALUES (";
                $query .= "$camp_Id,";
                $query .= "$this->budgetSpan,";
                $query .= "$this->budget,";
                $query .= "$this->budgetLimit,";
                $query .= "now(),now())";
                $result = mysql_query($query);
                if ($result != "1")
                {
                    $message = "アラーと情報登録失敗しました";
                    return $message;
                }

            }
            return $message;
        }

        function updateCampaign()
        {
            //まず、同じキャンペーン名チェック
            $query = "SELECT * FROM campaign WHERE ";
            $query .= "memberId=$this->memberId AND ";
            $query .= "listingType=$this->listingType AND ";
            $query .= "name='$this->campaignName' AND ";
            $query .= "camp_Id!=$this->camp_Id AND ";
            $query .= "status!=9";
            $result = mysql_query($query);
            //同じキャンペーン名がある場合、新規できません
            if(mysql_fetch_array($result))
            {
                $message = "同じキャンペーン名がある";
            }
            else
            {
                $query = "UPDATE campaign SET name='$this->campaignName',";
                $query .= "summarize='$this->campaignSummarize',";
                $query .= "dailyBudget=$this->dailyBudget,";
                if(isset($this->endDate) && $this->endDate != "")
                {
                    $query .= "endDay='$this->endDate $this->endHour:$this->endMin:$this->endSec',";
                }
                else
                {
                    $query .= "endDay=null,";
                }
                $query .= "networkTargeting='$this->networkTargeting',";
                $query .= "enableSeparateContentBids=$this->isEnableSeperateContentBids,";
                $query .= "enableBudgetOptimizer=$this->isEnableAutoOptimization,";
                $query .= "status=$this->status,";
                //同期状態は：更新待ち
                $query .= "sync=2,";
                $query .= "lastUpdate=now()";
                $query .= "WHERE camp_Id=$this->camp_Id";

                $result = mysql_query($query);
                if ($result != "1")
                {
                    $message = "更新失敗しました";
                }
                else
                {
                    $message =  "更新しました";
                }

                //アラーと情報を更新
                $query = "UPDATE alertschedule SET ";
                $query .= "campaignId=$this->camp_Id,";
                $query .= "period=$this->budgetSpan,";
                $query .= "alertBudget=$this->budget,";
                $query .= "conversionPremium=$this->budgetLimit,";
                $query .= "lastUpdate=now()";

                $result = mysql_query($query);
                if ($result != "1")
                {
                    $message = "アラーと情報更新失敗しました";
                    return $message;
                }
            }
            return $message;
        }

        function updateAllCampaigns()
        {
            $campaignIds = split(",",$_GET['campaignIds']);

            $ids = "(";
            for($i=0;$i<count($campaignIds)-1;$i++)
            {
                $ids .=$campaignIds[$i].",";
            }
            $ids .= $campaignIds[count($campaignIds)-1].")";

            if(isset($_POST['change_status']))
            {
                $query = "UPDATE campaign SET status=$this->status,";
                //未同期状態に設定
                $query .= "sync=2,lastUpdate=now() WHERE ";
                $query .= "camp_Id IN $ids";

                $result = mysql_query($query);
                if ($result != "1")
                {
                    $message = "更新失敗しました";
                }
                else
                {
                    $message =  "更新しました";
                }
            }

            return $message;

        }

        
    }
?>
